package com.batch.demo.domain.nestedJob;

import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.batch.core.repository.JobRepository;
import org.springframework.batch.core.step.builder.JobStepBuilder;
import org.springframework.batch.core.step.builder.StepBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.PlatformTransactionManager;

@Configuration
public class NestedDemo
{
    @Autowired
    private JobBuilderFactory jobBuilderFactory;

    @Autowired
    private StepBuilderFactory stepBuilderFactory;

    @Autowired
    private Job childJobOne;  // 与子Job 的命名要同名

    @Autowired
    private Job childJobTwo;

    @Autowired
    private JobLauncher launcher;

    // 父Job启动子Job
    @Bean
    public Job parentJob(JobRepository repository, PlatformTransactionManager platformTransactionManager) {
        return jobBuilderFactory.get("parentJob")
                .start(childJob1(repository, platformTransactionManager))
                .next(childJob2(repository, platformTransactionManager))
                .build();
    }

    //是Job类型的Step
    private Step childJob1(JobRepository repository, PlatformTransactionManager platformTransactionManager){
        return new JobStepBuilder(new StepBuilder("childJob1"))
                .job(childJobOne)
                .launcher(launcher)//使用启动父Job的启动对象
                .repository(repository)
                .transactionManager(platformTransactionManager)
                .build();
    }

    //是Job类型的Step
    private Step childJob2(JobRepository repository, PlatformTransactionManager platformTransactionManager){
        return new JobStepBuilder(new StepBuilder("childJob2"))
                .job(childJobTwo)
                .launcher(launcher)//使用启动父Job的启动对象
                .repository(repository)
                .transactionManager(platformTransactionManager)
                .build();
    }

}
